package com.example.aidlclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

import com.example.testing.ipcdemo.Book;
import com.example.testing.ipcdemo.IBookManager;
import com.example.testing.ipcdemo.IOnNewBookArrivedListener;

import java.util.List;

/**
 * Created by tangjiangxu on 9/8/17.
 */

public class BookManagerActivity extends Activity{
    private static final String TAG = "BookManagerActivity";
    private static final int MESSAGE_NEW_BOOK_ARRIVED = 100;
    private IBookManager mRemoteBookManager;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_NEW_BOOK_ARRIVED:
                    Log.e(TAG, "handleMessage: receive new book:" + msg.obj);
                    break;
            }
        }
    };

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG, "onServiceConnected: thread:"+Thread.currentThread().getName());
            final IBookManager iBookManager = IBookManager.Stub.asInterface(service);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mRemoteBookManager = iBookManager;
                        List<Book> list = iBookManager.getBookList();
                        Log.e(TAG, "onServiceConnected query book list,list.type="+list.getClass().getCanonicalName() );
                        Log.e(TAG, "onServiceConnected query book list:"+list.toString() );
                        Book newBook = new Book(3, "Android进阶");
                        iBookManager.addBook(newBook);
                        List<Book> newList = iBookManager.getBookList();
                        Log.e(TAG, "onServiceConnected query book newlist:"+newList.toString() );

                        iBookManager.registerLisenter(mONNewBookArrivedListener);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mRemoteBookManager = null;
            Log.e(TAG, "onServiceDisconnected: binder died" );
        }
    };

    private IOnNewBookArrivedListener mONNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onNewBookArrived(Book book) throws RemoteException {
            Log.e(TAG, "onNewBookArrived: thread :" + Thread.currentThread().getName());
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVED, book).sendToTarget();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_manager);
        findViewById(R.id.btn_getbooklist).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("com.example.testing.ipcdemo.BookManagerService");
                intent.setPackage("com.example.testing.ipcdemo");
                bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
                /*try {
                    mRemoteBookManager.getBookList();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }*/
            }
        });

        findViewById(R.id.btn_binder_pool).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent= new Intent(BookManagerActivity.this, BinderPoolActivity.class);
                startActivity(intent);
            }
        });

    }


    @Override
    protected void onDestroy() {
        if (mRemoteBookManager != null && mRemoteBookManager.asBinder().isBinderAlive()) {
            try {
                mRemoteBookManager.unRegisterLisenter(mONNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mConnection);
        super.onDestroy();
    }
}
